/*************************************************************************
	> File Name: server.c
	> Author: life
	> Created Time: Mon 26 Aug 2019 02:38:30 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>


#define BUF_SIZE  1024
#define BACKLOG	  10
/* socket
 * bind 
 * listen
 * accept
 * send/recv
 */

int main (int argc,char **argv)
{
	int server_fd;
	int client_fd;
	struct sockaddr_in ServerAddr;
	struct sockaddr_in ClientAddr;
	int iError;
	int clientlen;
	unsigned char RecvBUF[1000];
	int recvlen;

	signal(SIGCHLD,SIG_IGN);
	server_fd = socket(AF_INET,SOCK_STREAM,0);
	if (server_fd == -1)
	{
		printf("socket error\n");
		return -1;
	}

	ServerAddr.sin_family 		= AF_INET;
	ServerAddr.sin_port 		= htons(8080);
	ServerAddr.sin_addr.s_addr 	= INADDR_ANY;
	memset(ServerAddr.sin_zero , 0 ,8);

	iError = bind(server_fd,(struct sockaddr*)&ServerAddr,sizeof(struct sockaddr));
	if(iError < 0)
	{
		printf("bind error\n");
		return -1;
	}

	iError = listen(server_fd, BACKLOG);
	if(iError < 0)
	{
		printf("listen error\n");
		return -1;
	}

	
	while(1)
	{
		clientlen = sizeof(struct sockaddr);
		client_fd = accept(server_fd,(struct sockaddr*)&ClientAddr,&clientlen);
		if (client_fd)
		{
			printf("connect from %s \n",inet_ntoa(ClientAddr.sin_addr));
			if(!fork())
			{
				//子进程
				while(1)
				{
					recvlen = recv(client_fd,RecvBUF,999,0);
					if(recvlen <= 0)
					{
						close(server_fd);
						return -1;
					}
					else
					{
						RecvBUF[recvlen] = '\0';
						printf("%s: %s\n",inet_ntoa(ClientAddr.sin_addr), RecvBUF);
					}
				}
			}
		}
	}
	close(server_fd);
	return 0;
}
